<?php

namespace App\Http\Controllers\applet_api;

use App\Http\Controllers\Controller;
use App\Models\AppCourse;
use App\Models\AppOrder;
use App\Models\AppVip;
use App\Models\Information;
use App\Models\Integral;
use App\Models\Node;
use App\Models\Platform_user;
use App\Models\VipOrder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PayController extends Controller
{

    public function index(Request $Request)
    {
        //接受参数判断类型
        //course课程 node工艺节点 information资料
        // 支付状态 success fail afoot
        $type = $Request->type;
        //根据类型查询金额
        if($type == 'information'){
            $product = Information::where('id',$Request->id)->first();
        }
        if($type == 'node'){
            $product = Node::where('id',$Request->id)->first();
        }
        if($type == 'course'){
            $product = AppCourse::where('id',$Request->id)->where('status',1)->first();
        }
        
        if(!$product){
            return response()->json(['code' => '404', 'msg' => '商品已下架']);
        }
        
        //判断是否购买过
        $is = AppOrder::where('user_id',$Request->uid)->where('product_id',$Request->id)->where('type',$Request->type)->where('pay_status','success')->first();
        if($is){
            return response()->json(['code' => '500', 'msg' => '此商品已经购买过了']);
        }

        $integral = 0;
        $payment_method = 'wechat';
        $pay_status = 'afoot';
        //如果是积分支付
        if($product->integral > 0){
            //判断是否全是积分
            $integral = $product->integral;
            //扣除用户的积分
            $user_integral = Integral::where('uid',$Request->uid)->sum('score');
            if($user_integral < $integral){
                return response()->json(['code' => '500', 'msg' => '剩余积分不足']);
            }
            $payment_method = 'integral';
            $pay_status = 'success';
        }

        
        $amount = 1;
        $coupon = 0;//优惠券ID
        $no = 'NO'.uniqid();
        $price = $product->price;
        //生成订单
        $order = new AppOrder();
        $order->no = $no;
        $order->type = $type;
        $order->user_id = $Request->uid;
        $order->product_id = $Request->id;
        $order->product_sku_id = 0;
        $order->amount = $amount;
        $order->coupon = $coupon;
        $order->address = '';
        $order->integral = $integral;
        $order->total_amount = $price;
        $order->pay_amount = 0;//实际支付金额
        $order->pay_status = $pay_status;
        $order->paid_at = null;
        $order->payment_method = $payment_method;
        $order->payment_no = '';
        $order->extra = '';
        $order->closed = 0;
        
        if($product->integral > 0 && $product->price == 0){
            $order->paid_at = Date('Y-m-d H:i:s',time());
            $order->pay_status = 'success';
            try {
                DB::beginTransaction();
                $order->save();
                //扣除积分
                $integral_type = Integral::TYPE;
                $integral_typenamne = Integral::TYPENAME;
                $integral_insert = new Integral();
                $integral_insert->uid =  $Request->uid;
                $integral_insert->score =  0 - $integral;
                $integral_insert->type =  $integral_type[$Request->type];
                $integral_insert->content =  $order->no;
                $integral_insert->des =  $integral_typenamne[$Request->type];
                $integral_insert->create_time =  time();
                $integral_insert->update_time =  time();
                $integral_insert->save();
                DB::commit();
                return true;
            } catch (\Throwable $th) {
                Log::info(json_encode($th));
                return response()->json(['code' => '500', 'msg' => '支付发生错误']);
            }
            
            return response()->json(['code' => '201', 'msg' => '支付成功']);
        }

        $order->save();
        $openid = Platform_user::find($Request->uid)->openid;
        return response()->json(['code' => '200','no' => $order->no, 'data' => app('wechat_pay')->mp([
            'out_trade_no' => $order->no,  // 商户订单流水号，与支付宝 out_trade_no 一样
            'total_fee' => $order->total_amount * 100, // 与支付宝不同，微信支付的金额单位是分。
            'body'      => $product->title.'的订单：'.$order->no, // 订单描述
            'openid' => $openid,
        ])]);
    }


    
    public function vip(Request $Request)
    {
        //判断是否购买过
        $is = VipOrder::where('uid',$Request->uid)->where('vip_id',$Request->id)->where('status',1)->orderBy('id','desc')->first();
        $due_date = Date('Y-m-d',strtotime('+1 year'));
        if($is){
            //查询到期时间
            if(strtotime($is->due_date) > time()){
                $due_date = strtotime($is->due_date) + (3600*24*365);
                $due_date = Date('Y-m-d',$due_date);
            }
        }

        $product = AppVip::find($Request->id);
        $numbers = 'VIP'.uniqid();
        $price = $product->price;
        //生成订单
        $order = new VipOrder();
        $order->numbers = $numbers;
        $order->title = $product->title;
        $order->type = 0;
        $order->uid = $Request->uid;
        $order->due_date = $due_date;
        $order->price = $price;
        $order->pay = 0;//实际支付金额
        $order->pay_type = 1;
        $order->status = 0;
        $order->discount = 0;
        $order->vip_id = $product->id;
        $order->transaction_id = 0;
        $order->notice_info = '';
        $order->create_time = time();
        $order->update_time = time();
        $order->save();
        $openid = Platform_user::find($Request->uid)->openid;
        return response()->json(['code' => '200','numbers' => $order->numbers, 'data' => app('wechat_pay_vip')->mp([
            'out_trade_no' => $order->numbers,  // 商户订单流水号，与支付宝 out_trade_no 一样
            'total_fee' => $order->price * 100, // 与支付宝不同，微信支付的金额单位是分。
            'body'      => $product->title.'的订单：'.$order->numbers, // 订单描述
            'openid' => $openid,
        ])]);
    }


    public function isPay(Request $Request)
    {
        if(!$Request->no){
            return response()->json(['code' => '500', 'msg' => '参数错误']);
        }
        $is = AppOrder::where('no',$Request->no)->where('pay_status','success')->first();
        if(!$is){
            return response()->json(['code' => '200', 'data' => false]);
        }
        return response()->json(['code' => '200', 'data' => true]);
    }


    public function isPayVip(Request $Request)
    {
        if(!$Request->numbers){
            return response()->json(['code' => '403', 'msg' => '参数错误']);
        }
        $data = VipOrder::where('numbers', $Request->numbers)->where('status', 1)->first();
        if(empty($data)){
            return response()->json(['code' => '500', 'msg' => '未支付']);
        }
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$data]);
    }

    public function wechatNotify()
    {
        // 校验回调参数是否正确
        $data  = app('wechat_pay')->verify();
        // 找到对应的订单
        $order = AppOrder::where('no', $data->out_trade_no)->first();
        // 订单不存在则告知微信支付
        if (!$order) {
            return 'fail';
        }
        // 订单已支付
        if ($order->paid_at) {
            // 告知微信支付此订单已处理
            return app('wechat_pay')->success();
        }

        $order->paid_at = Date('Y-m-d H:i:s',time());
        $order->payment_no = $data->transaction_id;
        $order->pay_status = 'success';
        $order->pay_amount = $data->total_fee / 100;
        $order->extra = json_encode($data);
        $order->save();
        return app('wechat_pay')->success();
    }

    public function wechatNotifyVip()
    {
        // 校验回调参数是否正确
        $data  = app('wechat_pay_vip')->verify();
        // 找到对应的订单
        $order = VipOrder::where('numbers', $data->out_trade_no)->first();
        // 订单不存在则告知微信支付
        if (!$order) {
            $order->status = 2;
            $order->notice_info = json_encode($data);
            $order->save();
            return 'fail';
        }
        // 订单已支付
        if ($order->paid_at) {
            // 告知微信支付此订单已处理
            return app('wechat_pay_vip')->success();
        }

        $order->pay_date = Date('Y-m-d H:i:s',time());
        $order->transaction_id = $data->transaction_id;
        $order->status = 1;
        $order->pay = $data->total_fee / 100;
        $order->notice_info = json_encode($data);
        $order->save();
        return app('wechat_pay_vip')->success();
    }

}
